<script lang="ts" setup>
import { ref, onMounted, watch, onUnmounted, computed } from 'vue'
import classification from '../api/classification'
import utils from '../utils/utils'
import { debounce } from 'lodash-es'
import { useListStore } from '../store/list'
import { useUploadFile } from '../store/uploadFile'
import collection from '../api/collection'
import { status, StateProtect } from '../utils/classificationType'
import UploadExcell from './collection/uploadExcell.vue'
import { useCollectionSearchStore } from '../store/collection/collectionSearch'
import { exportExcel } from '../api/utils'
const collectionSearchStore = useCollectionSearchStore()
//获取列表数据
const listStore = useListStore()
const uploadFileStore = useUploadFile()
//const typeName = ref('')
const valueSelectClassification = ref('')
const valueSelectClassificationTrue = ref(true);

// 新增刷新控制变量
const refreshKey = ref(0)
const Classification = ref<any[]>([])

// 响应式窗口宽度
const windowWidth = ref<number>(window.innerWidth)

// 监听窗口大小变化
const handleResize = () => {
    windowWidth.value = window.innerWidth
}
// 计算属性判断是否为大屏显示
const isLargeScreen = computed(() => windowWidth.value > 768)

// 分类验证函数
const validateClassification = (tree: any[], targetValue: string): boolean => {
    return tree.some(node => {
        if ((node.value === targetValue)) {
            collectionSearchStore.typeName = node.label
            return true
        }
        if (node.children?.length) {
            return validateClassification(node.children, targetValue)
        }
        return false
    })
}
function getTedingCollection(inputName, typeName, valueSelectProtect, valueSelectState) {
    collection.getTeDingCollection(listStore.pageNum, listStore.pageSize, inputName, typeName, valueSelectProtect, valueSelectState).then(res => {
        listStore.tableData = res.data.data
        listStore.total = res.data.total
    })
}
// 正确的watch用法 ✅
watch(valueSelectClassification, debounce((newVal) => {
    if (newVal && !validateClassification(Classification.value, newVal)) {
        utils.showMessage('请输入正确分类', 'warning', 5000)
        // 添加延时避免直接清空导致UI闪烁
        valueSelectClassificationTrue.value = false
        setTimeout(() => {
            valueSelectClassification.value = ''
            refreshKey.value++
        }, 2000)
    }
    valueSelectClassificationTrue.value = true
}, 300))
const checkTypename = (tree: any[], targetValue: string): boolean => {
    return tree.some(node => {
        if (node.label === targetValue) {
            valueSelectClassification.value = node.value
            return true
        }
        if (node.children?.length) {
            return checkTypename(node.children, targetValue)
        }
        return false
    })
}
function uploadFile() {
    uploadFileStore.setIsOpen(true)
}
function excelLoading() {
    console.log('开始导出')
    /*exportExcel('collection')*/
}
watch(() => collectionSearchStore.typeName, debounce((newVal) => {
    if (newVal === '') {
        // 立即清空分类选择
        valueSelectClassification.value = ''
        valueSelectClassificationTrue.value = true
        return
    }
    if (newVal && !checkTypename(Classification.value, newVal)) {
        utils.showMessage('请输入正确分类', 'warning', 5000)
        // 添加延时避免直接清空导致UI闪烁
        valueSelectClassificationTrue.value = false
        setTimeout(() => {
            valueSelectClassification.value = ''
        }, 2000)
    }
}, 1000))
watch(valueSelectClassification, (newVal) => {
    if (newVal === '') {
        collectionSearchStore.typeName = '' // 确保双向同步
        refreshKey.value++ // 强制刷新组件
    }
})

onMounted(async () => {
    await classification.getClassification().then((res) => {
        Classification.value = res.data.data
    })
    window.addEventListener('resize', handleResize)
})
onUnmounted(() => {
    window.removeEventListener('resize', handleResize)
})

</script>
<template>
    <div class="InputIcon">
        <div class="InputClass">
            <div><span>保存状态</span><el-tree-select v-model="collectionSearchStore.valueSelectProtect"
                    :data="StateProtect.StateProtect" clearable check-strictly :render-after-expand="false"
                    style="width: 240px" /></div>
            <div><span>分类</span><el-tree-select v-model="valueSelectClassification" :data="Classification"
                    check-strictly :render-after-expand="false" style="width: 240px" /></div>
            <div><span>当前状态</span><el-tree-select :key="refreshKey" v-model="collectionSearchStore.valueSelectState"
                    :data="status.State" clearable check-strictly :render-after-expand="false" style="width: 240px" />
            </div>
        </div>
        <div class="InputClass" v-if="isLargeScreen">
            <div><span>藏品名称</span> <el-input v-model="collectionSearchStore.inputName" style="width: 240px;"
                    placeholder="请输入藏品名称" clearable /></div>
            <div><span>分类</span> <el-input v-model="collectionSearchStore.typeName" style="width: 240px;"
                    placeholder="请输入分类名称" clearable />
            </div>
            <el-button type="primary"
                @click="getTedingCollection(collectionSearchStore.inputName, collectionSearchStore.typeName, collectionSearchStore.valueSelectProtect, collectionSearchStore.valueSelectState)">搜索</el-button>
            <el-button type="primary">重置</el-button>
        </div>
        <div class="InputClass" v-if="!isLargeScreen">
            <div style="display: flex;"><span>藏品名称</span> <el-input v-model="collectionSearchStore.inputName"
                    style="width: 240px;display:inline-block" placeholder="请输入藏品名称" clearable /></div>
            <div style="display: flex;"><span>分类 </span><el-input v-model="collectionSearchStore.typeName"
                    style="width: 240px;display:inline-block" placeholder="请输入分类名称" clearable /></div>
        </div>
        <div class="InputClass" v-if="isLargeScreen">
            <el-button type="success" @click="uploadFile"><el-icon>
                    <Upload />
                </el-icon>导入</el-button>
            <el-button type="warning" @click="excelLoading"><el-icon>
                    <Download />
                </el-icon>导出</el-button>
        </div>
        <div class="InputClassButton" v-if="!isLargeScreen">
            <el-button type="primary"
                @click="getTedingCollection(collectionSearchStore.inputName, collectionSearchStore.typeName, collectionSearchStore.valueSelectProtect, collectionSearchStore.valueSelectState)">搜索</el-button>
            <el-button type="primary">重置</el-button>
            <el-button type="success" @click="uploadFile"><el-icon>
                    <Upload />
                </el-icon>导入</el-button>
            <el-button type="warning" @click="excelLoading"><el-icon>
                    <Download />
                </el-icon>导出</el-button>
        </div>
    </div>
    <UploadExcell />
</template>

<style scoped>
.InputIcon {
    display: grid;
    justify-content: left;
    align-items: center;
    gap: 1rem;
}

.InputClass {
    display: flex;
    justify-content: left;
    align-items: center;
    gap: 1rem;
}

div span {
    margin-right: 1rem;
}

:deep(.el-button) {
    display: inline-flex !important;
    align-items: center;
    justify-content: center;
}

:deep(.el-button span) {
    flex: 1;
    text-align: center;
}

@media (max-width: 768px) {
    .InputIcon {
        display: inline-grid;
        justify-content: center;
        align-items: center;
        gap: 12px;
    }

    .InputClass {
        display: inline-grid;
        flex-direction: row !important;
        flex-wrap: wrap;
        align-items: center;
        gap: 8px;
        width: 100%;
    }

    .InputClassButton {
        display: flex;
        justify-content: center;
        align-items: center;
    }

    .InputClassButton :deep(.el-button) {
        padding-left: 1rem;
    }

    .el-input,
    .el-tree-select {
        flex: 1 1 120px;
        min-width: 0;
        width: 100% !important;
    }

    .el-button {
        flex: 1 1 0;
        min-width: 0;
        width: auto !important;
        margin-bottom: 0;
        font-size: 15px;
        padding: 10px 0;
    }
}
</style>